<template>
  <div class="chart-card">
    <el-card class="chart-container-card">
      <template #header>
        <div class="card-header">
          <span>农产品合格证打印次数</span>
        </div>
      </template>
      <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
    </el-card>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { getQuantityGroupById } from '@/api/nongjt/showData'
import { onMounted, onBeforeUnmount, ref, nextTick } from 'vue'

const chartContainer = ref(null)
let chart = null

// 初始化图表
function initChart() {
  chart = echarts.init(chartContainer.value)
  updateChart()
}

// 更新图表数据
async function updateChart() {
  try {
    const response = await getQuantityGroupById()
    const data = response.rows
    console.log(data)
    // 处理数据格式
    const chartData = data.map(item => ({
      name: item.productionEntity || '未知产品',
      value: item.printCount
    }))

    // 定义颜色列表，确保不同类型的显示不同颜色
    const colors = [
      '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
      '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#5470c6'
    ]

    const option = {
      title: {
        text: '合格证打印次数分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: 10,
        top: 20,
        bottom: 20,
        data: chartData.map(item => item.name)
      },
      series: [
        {
          name: '合格证打印次数',
          type: 'pie',
          radius: '55%',
          center: ['40%', '50%'],
          data: chartData,
          color: colors, // 应用颜色列表
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }

    chart.setOption(option)
  } catch (error) {
    console.error('获取图表数据失败:', error)
  }
}

// 窗口大小改变时重置图表大小
function resizeChart() {
  if (chart) {
    chart.resize()
  }
}

onMounted(() => {
  nextTick(() => {
    initChart()
    window.addEventListener('resize', resizeChart)
  })
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  if (chart) {
    chart.dispose()
  }
})

defineExpose({
  updateChart
})
</script>

<style scoped>
.chart-card {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 500px;
}

.chart-container-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

/* 可选：自定义滚动条样式 */
:deep(.el-card__body) {
  padding: 20px;
}
</style>
